/**
 * Copyright (c) 2011, JFXtras
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package jfxtras.scene.control;

import java.math.BigInteger;

import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventTarget;
import javafx.event.EventType;
import javafx.scene.Node;
import javafx.scene.control.Control;
import javafx.scene.control.Label;
import javafx.util.Callback;

/**
 * 
 * @author Tom Eugelink
 * TODO: use a ListView cell renderer? 
 */
public class SpinnerX<T> extends Control
{
	// ==================================================================================================================
	// CONSTRUCTOR
	
	/**
	 * 
	 */
	public SpinnerX(SpinnerXDataProvider<T> model, T startValue)
	{
		setDataProvider(model);
		setValue(startValue);
		construct();
	}
	
	/*
	 * 
	 */
	private void construct()
	{
		// setup the CSS
		// the -fx-skin attribute in the CSS sets which Skin class is used
		this.getStyleClass().add(this.getClass().getSimpleName().toLowerCase());
	}

	/**
	 * Return the path to the CSS file so things are setup right
	 */
	@Override protected String getUserAgentStylesheet()
	{
		return this.getClass().getResource(this.getClass().getSimpleName() + ".css").toString();
	}
	
	// ==================================================================================================================
	// PROPERTIES
	
	/** Value: */
	public ObjectProperty<T> valueProperty() { return iValueObjectProperty; }
	final private ObjectProperty<T> iValueObjectProperty = new SimpleObjectProperty<T>(this, "value", null);
	// java bean API
	public T getValue() { return iValueObjectProperty.getValue(); }
	public void setValue(T value) { iValueObjectProperty.setValue(value); }
	public SpinnerX<T> withValue(T value) { setValue(value); return this; }

	/** convenience */
	public void setValueByIndex(BigInteger idx) {
		setValue( getDataProvider().getValue( idx ) );
	}
	public void setValueByIndex(long idx) { setValueByIndex( BigInteger.valueOf(idx)); }
	public BigInteger setValueIndex() { return getDataProvider().getIdx( getValue() ); }
	
	/** Cyclic: */
	public ObjectProperty<Boolean> cyclicProperty() { return iCyclicObjectProperty; }
	final private ObjectProperty<Boolean> iCyclicObjectProperty = new SimpleObjectProperty<Boolean>(this, "cyclic", null);
	// java bean API
	public Boolean getCyclic() { return iCyclicObjectProperty.getValue(); }
	public void setCyclic(Boolean value) { iCyclicObjectProperty.setValue(value); }
	public SpinnerX<T> withCyclic(Boolean value) { setCyclic(value); return this; }

	/** DataProvider: */
	public ObjectProperty<SpinnerXDataProvider<T>> dataProviderProperty() { return iDataProviderObjectProperty; }
	final private ObjectProperty<SpinnerXDataProvider<T>> iDataProviderObjectProperty = new SimpleObjectProperty<SpinnerXDataProvider<T>>(this, "dataProvider", null);
	// java bean API
	public SpinnerXDataProvider<T> getDataProvider() { return iDataProviderObjectProperty.getValue(); }
	public void setDataProvider(SpinnerXDataProvider<T> value) { iDataProviderObjectProperty.setValue(value); }
	public SpinnerX<T> withDataProvider(SpinnerXDataProvider<T> value) { setDataProvider(value); return this; }

	/** CellFactory: */
	public ObjectProperty<Callback<T, Node>> cellFactoryProperty() { return iCellFactoryObjectProperty; }
	final private ObjectProperty<Callback<T, Node>> iCellFactoryObjectProperty = new SimpleObjectProperty<Callback<T, Node>>(this, "cellFactory", new DefaultCellFactory());
	// java bean API
	public Callback<T, Node> getCellFactory() { return iCellFactoryObjectProperty.getValue(); }
	public void setCellFactory(Callback<T, Node> value) { iCellFactoryObjectProperty.setValue(value); }
	public SpinnerX<T> withCellFactory(Callback<T, Node> value) { setCellFactory(value); return this; }

	// ==================================================================================================================
	// CellFactory
	
	/**
	 * Default cell factory
	 */
	class DefaultCellFactory implements Callback<T, Node>
	{
		private Label label = null;
		
		@Override
		public Node call(T value)
		{
			if (this.label == null) this.label = new Label();
			this.label.setText( value == null ? "-" : value.toString() );
			return this.label;
		}
	};
	
	// ==================================================================================================================
	// EVENTS
	
	/** OnCycle: */
	public ObjectProperty<EventHandler<CycleEvent>> onCycleProperty() { return iOnCycleObjectProperty; }
	final private ObjectProperty<EventHandler<CycleEvent>> iOnCycleObjectProperty = new SimpleObjectProperty<EventHandler<CycleEvent>>(null);
	// java bean API
	public EventHandler<CycleEvent> getOnCycle() { return iOnCycleObjectProperty.getValue(); }
	public void setOnCycle(EventHandler<CycleEvent> value) { iOnCycleObjectProperty.setValue(value); }
	public SpinnerX<T> withOnCycle(EventHandler<CycleEvent> value) { setOnCycle(value); return this; }
	final static public String ONCYCLE_PROPERTY_ID = "onCycle";
	
	/**
	 * CycleEvent 
	 */
	static public class CycleEvent extends Event
	{
		/**
		 * 
		 */
		public CycleEvent()
		{
			super(new EventType<CycleEvent>());
		}

		/**
		 * 
		 * @param source
		 * @param target
		 */
		public CycleEvent(Object source, EventTarget target)
		{
			super(source, target, new EventType<CycleEvent>());
		}
		
		public BigInteger getOldIdx() { return this.oldIdx; }
		private BigInteger oldIdx;
		
		public BigInteger getNewIdx() { return this.newIdx; }
		private BigInteger newIdx;
		
		
		public boolean cycledDown() { return this.oldIdx.compareTo(this.newIdx) > 0; }
		public boolean cycledUp() { return this.oldIdx.compareTo(this.newIdx) < 0; }
	}
	
	/**
	 * we're cycling, fire the event
	 */
	public void fireCycleEvent(BigInteger oldIdx, BigInteger newIdx)
	{
		EventHandler<CycleEvent> lCycleEventHandler = getOnCycle();
		if (lCycleEventHandler != null)
		{
			CycleEvent lCycleEvent = new CycleEvent();
			lCycleEvent.oldIdx = oldIdx;
			lCycleEvent.newIdx = newIdx;
			lCycleEventHandler.handle(lCycleEvent);
		}
	}
	
	
	// ==================================================================================================================
	// BEHAVIOR
	
	/**
	 * 
	 */
	public void decrease()
	{
		// get the dataprovider
		SpinnerXDataProvider<T> lDataProvider = getDataProvider(); 
		if (lDataProvider != null) {
			
			// get the current index
			BigInteger lOldIdx = lDataProvider.getIdx(getValue());
			
			// get the previous index (usually current - 1)
			BigInteger lIdx = lDataProvider.getPreviousIdx(lOldIdx);
			
			// if null is return, there is no previous index
			if (lIdx == null)
			{
				// if we're not cyclic
				if (getCyclic() != null && getCyclic().booleanValue() == false)
				{
					// do nothing
					return;
				}
				
				// cycle to the other end
				lIdx = lDataProvider.getPreviousIdx(null);
				
				// notify listener that we've cycled
				fireCycleEvent(lOldIdx, lIdx);
			}
			
			// get the value for the new index
			T lValue = lDataProvider.getValue(lIdx);
			
			// set it
			setValue(lValue);
		}
	}
	
	/**
	 * 
	 */
	public void increase()
	{
		// get the data provider
		SpinnerXDataProvider<T> lDataProvider = getDataProvider(); 
		if (lDataProvider != null) {
			
			// get the current index
			BigInteger lOldIdx = lDataProvider.getIdx(getValue());
			
			// get the next index
			BigInteger lIdx = lDataProvider.getNextIdx(lOldIdx);
			
			// if null is return, there is no next index (usually current + 1)
			if (lIdx == null)
			{
				// if we're not cyclic
				if (getCyclic() != null && getCyclic().booleanValue() == false)
				{
					// do nothing
					return;
				}
				
				// cycle to the other end
				lIdx = lDataProvider.getNextIdx(null);
				
				// notify listener that we've cycled
				fireCycleEvent(lOldIdx, lIdx);
			}
			
			// get the value of the new index
			T lValue = lDataProvider.getValue(lIdx);
			
			// set the value
			setValue(lValue);
		}
	}

}
